/*
 * @Author: jiu yin
 * @Date: 2023-05-11 13:52:59
 * @LastEditTime: 2024-06-28 16:32:27
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\utils\index.js
 * jiu
 */


/**
 * @description:  深拷贝
 * @return {*}
 */


export function deepClone(obj) {
    const typeOfStr = Object.prototype.toString;
    const objType = typeOfStr.call(obj).slice(8, -1);
    // console.log(obj);
    if (objType !== 'Object' && objType !== 'Array') return obj;

    let newObj = objType === 'Array' ? [] : {};

    if (objType == "Object") {
        for (let key in obj) {
            newObj[key] = deepClone(obj[key]);
        }
    }

    if (objType == "Array") {
        obj.forEach((item, index) => {
            newObj.push(deepClone(item));
        });
    }


    return newObj;
}


//promise微任务
export function asyncFn(fn) {
    return Promise.resolve().then(fn);
}
//mutation微任务
export function mutationFn(fn) {
    let ob = new MutationObserver(fn);
    let text = document.createTextNode("0");
    ob.observe(text, { characterData: true });
    text.data = 1;
}

/**
 * 格式化
 * @param { Date } day
 * @param { String } fmt
 * @returns { String } time
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null;
    }
    const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
    let date;
    if (typeof time === "object") {
        date = time;
    } else {
        if (typeof time === "string") {
            if (/^[0-9]+$/.test(time)) {
                // support "1548221490638"
                time = parseInt(time);
            } else {
                time = time.replace(new RegExp(/-/gm), "/");
            }
        }

        if (typeof time === "number" && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay(),
    };
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === "a") {
            return ["日", "一", "二", "三", "四", "五", "六"][value];
        }
        return value.toString().padStart(2, "0");
    });
    return time_str;
}


//判断数据类型
export function typeOf(obj) {
    const toString = Object.prototype.toString.call(obj);
    return toString.slice(8, -1);
}


// 获取路由传参
export function getParams() {
    const searchParams = new URLSearchParams(window.location.search);
    const params = {};
    for (const [key, value] of searchParams.entries()) {
        params[key] = value;
    }
    return params;
}
//16进制颜色
export function getRandomHexColor() {
    return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0');
}

//颜色数组
export function getColorArr() {
    return ['#f50', '#2db7f5', '#87d068', '#108ee9',];
}

//对比版本号
export const comparisonVersion = (str1, str2) => {
    if (!str1 && !str2) return console.error("对比版本号 str1和str2必传");
    //相等
    if (str1 === str2) return "eq";

    let arr1 = str1.split(".");
    let arr2 = str2.split(".");

    for (let i = 0, len = arr1.length; i < len; i++) {
        if (arr1[i] > arr2[i]) return "max";
        if (arr1[i] < arr2[i]) return "min";
    }
};


//路由处理拼接path
export function dispose(arr, hidden = false) {

    // 过滤第一项的layout 路由
    let newArr = arr.map(item => {
        if (item.children.length == 1) {
            item.children.path = item.path + '/' + item.children[0].path;
            item.children.meta = item.meta;
            return item.children;
        } else {
            return item;
        }
    });

    //递归layout 要的结构体
    let recursion = (obj, arr) => {

        //false 不要hidden
        let newArr;
        if (!hidden) {
            newArr = arr.filter(item => !item.meta?.hidden);
        } else {
            newArr = arr;
        }

        if (newArr.length == 0) return null;
        return newArr.map(item => {
            //@ts-ignore
            let key = obj.pathDeep ? obj.pathDeep + '/' + item.path : item.path;
            item.pathDeep = key;
            return {
                path: key,
                label: item.meta.name,
                meta: item.meta,
                children: item.children ? recursion(item, item.children) : null
            };
        });
    };


    return recursion({}, newArr);
}



/**
 * @description:
 * @param {*} duration 时间
 * @param {*} from 来自
 * @param {*} to 去到
 * @param {*} callback 回调
 * @param {*} animation 动画
 * @return {*}
 */


function move(options, callback,) {
    let { duration = 1000, from = 0, to = 10, animation = "easeInOut" } = options;
    function warp(resolve, reject) {
        let obj_animation = {
            //线性
            linear(t) {
                return t;
            },
            //缓入
            easeIn(t) {
                return t * t;
            },
            //缓出
            easeOut(t) {
                return 1 - Math.pow(1 - t, 2);
            },
            //缓入缓出
            easeInOut(t) {
                return 0.5 - Math.cos(t * Math.PI) / 2;
            },
            //弹性
            elastic(t) {
                return 0.04 * t / Math.sin(25 * t + 7.5);
            },
            //反弹
            bounce(t) {
                if (t < 1 / 2.75) {
                    return 7.5625 * t * t;
                } else if (t < 2 / 2.75) {
                    t -= 1.5 / 2.75;
                    return 7.5625 * t * t + 0.75;
                } else if (t < 2.5 / 2.75) {
                    t -= 2.25 / 2.75;
                    return 7.5625 * t * t + 0.9375;
                } else {
                    t -= 2.625 / 2.75;
                    return 7.5625 * t * t + 0.984375;
                }
            }
        };


        let dis = to - from; //需要执行距离
        let speed = dis / duration; //速度
        let start_time = Date.now(); //开始时间
        let value = from; //当前值


        function _run() {
            let now = Date.now(); //开始时间
            let end_time = now - start_time; // 过去的时间差

            if (end_time > duration) {
                value = to;
                callback(value);
                resolve(value);
                return; //结束
            }
            let progress = end_time / duration; // 动画进度（从0到1）
            let eased_progress = obj_animation[animation](progress); // 使用缓动函数计算经过缓动后的进度
            let d = end_time * speed; //已经移动的距离
            value = from + d * eased_progress; //当前值
            callback(value);
            requestAnimationFrame(_run);
        }
        requestAnimationFrame(_run);
    }


    return new Promise(warp);
}


//性别
export function sexSwitch(sex) {
    let str = '';
    switch (sex) {
        case 0:
            str = '未知';
            break;
        case 1:
            str = '男';
            break;
        case 2:
            str = '女';
            break;
    }
    return str;
}


//支付方式
export function pay_type(pay_type) {
    let str = '';
    switch (pay_type) {
        case 1:
            str = '碳晶币';
            break;
        case 2:
            str = '微信';
            break;

    }
    return str;
}
// 防抖
export const debounce = (fn, delay = 1000) => {
    let timer = null;
    return function (args) {
        console.log(args);
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            fn(args);
        }, delay);
    };
};


// 节流
export const throttle = (fn, delay = 1000) => {
    let timer = null;
    let isOpen = true;

    return function (args) {
        if (!isOpen) return
        isOpen = false;
        if (!timer) {
            timer = setTimeout(() => {
                fn(args);
                clearTimeout(timer);
                timer = null;
                isOpen = true;
            }, delay);
        }
    };
}


// 下载
export const upload_url = (url, file_name) => {
    let a = document.createElement("a");
    if (!url) { throw new Error("请传入URL地址"); }
    let suffix = url.split(".")[1];
    file_name = file_name ? `${file_name}.${suffix}` : `${new Date().getTime()}.${suffix}`;
    a.setAttribute("download", file_name);
    a.href = url;
    a.click();
};



// oss封面
export const oss_cover = (h = 600) => {
    return `?x-oss-process=video/snapshot,t_3000,f_jpg,w_800,h_${h},m_fast `;
};
// file 格式
export const file_type = (key = "video") => {
    let obj = {
        video: "video",
        audio: "audio",
        image: "image",
        office: "application",
        xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        xls: "application/vnd.ms-excel"
    };
    return obj[key];
};

// 获取后缀
export const getSuffix = (str = "x.x") => {
    return str.split(".").at(-1);
};

// 千分位
export const thousands = (num) => {
    if (typeof num == "string") {
        num = Number(num)
    }
    if (typeof num != "number") {
        return console.error("千分位请传参number");
    }
    return num.toLocaleString()
};

// 数字转万
export const myriad_str = (num) => {
    if (typeof num == "string") {
        num = Number(num)
    }
    if (typeof num != "number") {
        return console.error("数字转万请传参number");
    }
    if (num / 10000 > 1) {
        let multiple = parseInt(num / 10000)
        let remaining = parseInt(num - multiple * 10000)
        return `${multiple}万${remaining ? remaining : ''}`
    } else {
        return num
    }
};

// 字节B转MB
export function b_to_mb(size) {
    if (!size) return 0
    return (Number(size) / 1024 / 1024).toFixed(2)
}

